package com.fubowen.lepton.helper

import android.content.Context
import android.graphics.BitmapFactory
import com.fubowen.lepton.helper.ImageHelper.bitmapToFavicon
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.util.concurrent.TimeUnit

object HttpHelper {

    private val httpClient: OkHttpClient by lazy {
        OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build()
    }

    suspend fun get(url: String): Response = withContext(Dispatchers.IO) {
        val request = Request.Builder().url(url).build()
        httpClient.newCall(request).execute()
    }

    suspend fun downloadImage(context: Context, url: String, filePath: String): String {
        val path = context.externalCacheDir!!.absolutePath + filePath
        return get(url).body.byteStream().let {
            bitmapToFavicon(BitmapFactory.decodeStream(it), path)
        }
    }
}

